package com.yao.yaoojbackendjudgeservice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.yao.yaoojbackendjudgeservice.judge.JudgeService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * rabbitmq 消息消费者
 */
@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private JudgeService judgeService;
    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {"yaooj_queue"}, ackMode = "MANUAL") //监听消息队列的名称，ackMode：手动确认还是默认回复 MANUAL:手动确认
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        //把string类型转换成Long类型
        long questionSubmitId=Long.parseLong(message);
        try {
            judgeService.doJudge(questionSubmitId);
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            //todo 如果处理失败了，就拒绝消息，并重新放入死信队列，再去做额外的处理
            channel.basicNack(deliveryTag, false, false);//最后一个参数：requeue（失败之后是否重新处理？此处是不要重新入队）
        }


    }
}